package cn.qn.service.impl.user;

import cn.qn.base.PageVO;
import cn.qn.dto.news.ImageTextDTO;
import cn.qn.dto.user.*;
import cn.qn.enums.AppUserSexEnum;
import cn.qn.enums.AppUserStatusEnum;
import cn.qn.enums.AppUserTypeEnum;
import cn.qn.exceptions.BizException;
import cn.qn.mapper.user.AppUserMapper;
import cn.qn.moudle.user.AppUser;
import cn.qn.moudle.user.AppUserAttention;
import cn.qn.repository.user.AppUserAttentionRepository;
import cn.qn.repository.user.AppUserRepository;
import cn.qn.service.user.AppUserService;
import cn.qn.utils.SerialNoUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: Bryant
 * @Date: 2018/6/11
 * @Description:
 */
@com.alibaba.dubbo.config.annotation.Service(interfaceClass = AppUserService.class)
@Service
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private AppUserAttentionRepository appUserAttentionRepository;
    @Resource
    private AppUserMapper appUserMapper;

    @Value("${aliyun.oss.showUrl}")
    private String showUrl;

    @Override
    public AppUser findByUserId(String userId) {
        return appUserRepository.findByUserId(userId);
    }

    @Override
    public AppUser findByMobile(String mobile) {
        return appUserRepository.findByMobile(mobile);
    }

    @Override
    public AppUser createAppUser(RegisterDTO dto) throws BizException{
        if(checkMobileExist(dto.getMobile())){
            throw new BizException("手机号码已被注册");
        }
        AppUser appUser = new AppUser();
        appUser.setUserId(SerialNoUtils.createUserId());
        appUser.setUserType(AppUserTypeEnum.NORMAL_USER.getCode());
        appUser.setMobile(dto.getMobile());
        appUser.setLoginPass(StringUtils.isNotEmpty(dto.getPassword())?new BCryptPasswordEncoder().encode(dto.getPassword()):null);
        appUser.setNickName(StringUtils.isNotEmpty(dto.getNickName())?dto.getNickName():dto.getMobile().substring(7));
        appUser.setHeadImg(dto.getHeadImg());
        appUser.setSex(AppUserSexEnum.SECRET.getCode());
        appUser.setScore(0);
        appUser.setStatus(AppUserStatusEnum.NORMAL.getCode());
        appUser = appUserRepository.save(appUser);
        //关注所有平台账号
        attentionPlatformUser(appUser.getUserId());
        return appUser;
    }

    @Override
    public boolean checkMobileExist(String mobile) {
        AppUser appUser = appUserRepository.findByMobile(mobile);
        if(null!=appUser){
            return true;
        }
        return false;
    }

    @Override
    public void attentionPlatformUser(String userId) {
        List<AppUser> platUsers = appUserRepository.findByUserType(AppUserTypeEnum.PLATFORM_USER.getCode());
        platUsers.forEach(u->{
            AppUserAttention attention =new AppUserAttention();
            attention.setUserId(userId);
            attention.setAttentionId(u.getUserId());
            appUserAttentionRepository.save(attention);
        });
    }

    @Override
    public void attentionByNormalUser(String attentionId) {
        List<AppUser> platUsers = appUserRepository.findByUserType(AppUserTypeEnum.NORMAL_USER.getCode());
        platUsers.forEach(u->{
            AppUserAttention attention =new AppUserAttention();
            attention.setUserId(u.getUserId());
            attention.setAttentionId(attentionId);
            appUserAttentionRepository.save(attention);
        });
    }

    @Override
    public PageVO<AppUserDTO> pageQueryAppUsers(AppUserQueryDTO query) {
        PageBounds pb = new PageBounds(query.getPageBounds().getPage(), query.getPageBounds().getLimit());
        List<AppUserDTO> list = appUserMapper.pageQueryAppUsers(query, pb);
        list.forEach(dto->{
            dto.setShowUserType(AppUserTypeEnum.getDesc(dto.getUserType()));
            dto.setShowSex(AppUserSexEnum.getDesc(dto.getSex()));
            dto.setShowStatus(AppUserStatusEnum.getDesc(dto.getStatus()));
            dto.setFullHeadImg(showUrl+dto.getHeadImg());

        });
        Integer count = appUserMapper.pageQueryAppUsersCount(query);
        return PageVO.convert(pb.getPage(), pb.getLimit(), list, count);
    }

    @Override
    public AppUserDTO queryDetailById(String userId) {
        AppUserDTO dto = new AppUserDTO();
        AppUser appUser = appUserRepository.findByUserId(userId);
        BeanUtils.copyProperties(appUser,dto);
        dto.setShowUserType(AppUserTypeEnum.getDesc(dto.getUserType()));
        dto.setShowSex(AppUserSexEnum.getDesc(dto.getSex()));
        dto.setShowStatus(AppUserStatusEnum.getDesc(dto.getStatus()));
        dto.setFullHeadImg(showUrl+dto.getHeadImg());
        dto.setCreateTime(DateFormatUtils.format(appUser.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        return dto;
    }

    @Override
    public void editStatus(AppUserDTO dto) throws BizException{
        AppUser appUser=appUserRepository.findByUserId(dto.getUserId());
        if(appUser==null){
            throw new BizException("该用户不存在");
        }
        appUser.setStatus(dto.getStatus());
        appUser.setUpdateBy(dto.getUpdateBy());
        appUser.setUpdateTime(new Date());
        appUserRepository.save(appUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser addPlatAppUser(AppUserAddDTO dto) {
        if(checkMobileExist(dto.getMobile())){
            throw new BizException("手机号码已被注册");
        }
        AppUser appUser = new AppUser();
        appUser.setUserId(SerialNoUtils.createUserId());
        appUser.setUserType(AppUserTypeEnum.PLATFORM_USER.getCode());
        appUser.setMobile(dto.getMobile());
        appUser.setHeadImg(dto.getHeadImg());
        appUser.setLoginPass(StringUtils.isNotEmpty(dto.getPassword())?new BCryptPasswordEncoder().encode(dto.getPassword()):null);
        appUser.setNickName(StringUtils.isNotEmpty(dto.getNickName())?dto.getNickName():dto.getMobile().substring(7));
        appUser.setSex(AppUserSexEnum.SECRET.getCode());
        appUser.setStatus(AppUserStatusEnum.NORMAL.getCode());
        appUser.setSignature(dto.getSignature());
        appUser.setCreateBy(dto.getCreateBy());
        appUser = appUserRepository.save(appUser);
        //关注被所有注册用户关注
        attentionByNormalUser(appUser.getUserId());
        return appUser;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppUser editPlatAppUser(AppUserEditDTO dto) throws BizException{
        AppUser appUser = appUserRepository.findByUserId(dto.getUserId());
        if(null==appUser){
            throw new BizException("未找到该用户");
        }
        if(!appUser.getMobile().equals(dto.getMobile())){
            if(checkMobileExist(dto.getMobile())){
                throw new BizException("手机号码已被注册");
            }
        }
        appUser.setMobile(dto.getMobile());
        appUser.setHeadImg(dto.getHeadImg());
        appUser.setNickName(dto.getNickName());
        appUser.setSignature(dto.getSignature());
        appUser.setUpdateBy(dto.getUpdateBy());
        appUser.setUpdateTime(new Date());
        appUserRepository.save(appUser);
        return appUser;
    }

    @Override
    public void resetPassword(AppUserResetPwdDTO dto) {
        AppUser appUser = appUserRepository.findByUserId(dto.getUserId());
        if(null==appUser){
            throw new BizException("未找到该用户");
        }
        appUser.setLoginPass(new BCryptPasswordEncoder().encode(dto.getPassword()));
        appUser.setUpdateBy(dto.getUpdateBy());
        appUser.setUpdateTime(new Date());
        appUserRepository.save(appUser);
    }

    @Override
    public List<AppUser> queryPlatUserList() {
        return appUserRepository.findByUserType(AppUserTypeEnum.PLATFORM_USER.getCode());
    }

    @Override
    public List<AppUserAttentionDTO> queryMyAttentions(String userId) {
        List<AppUserAttentionDTO> attentions = appUserMapper.queryMyAttentions(userId);
        attentions.forEach(a->{
            a.setHeadImg(showUrl+a.getHeadImg());
        });
        return attentions;
    }

    @Override
    public List<AppUserAttentionDTO> queryMyThreeAttentions(String userId) {
        List<AppUserAttentionDTO> attentions = appUserMapper.queryMyThreeAttentions(userId);
        attentions.forEach(a->{
            a.setHeadImg(showUrl+a.getHeadImg());
        });
        return attentions;
    }

    @Override
    public void attentionOneUser(String userId, String attentionId) throws BizException{
        AppUserAttention checkAttention = appUserAttentionRepository.findByUserIdAndAttentionId(userId,attentionId);
        if(null!=checkAttention){
            throw new BizException("用户已关注过了");
        }
        AppUserAttention attention=new AppUserAttention();
        attention.setUserId(userId);
        attention.setAttentionId(attentionId);
        attention.setCreateTime(new Date());
        appUserAttentionRepository.save(attention);
    }

    @Override
    public void cancleAttentionOneUser(String userId, String attentionId) throws BizException {
        AppUserAttention attention = appUserAttentionRepository.findByUserIdAndAttentionId(userId,attentionId);
        if(null==attention){
            throw new BizException("未关注该用户");
        }
        appUserAttentionRepository.delete(attention);
    }

    @Override
    public List<String> queryAttionUserIds(String userId) {
        List<AppUserAttention> attentions =appUserAttentionRepository.findByUserId(userId);
        List<String> userIds= new ArrayList<>();
        attentions.forEach(a->{
            userIds.add(a.getAttentionId());
        });
        return userIds;
    }

    @Override
    public Integer countByUserId(String userId) {
        return appUserAttentionRepository.countByUserId(userId);
    }

    @Override
    public Integer countByAttentionId(String userId) {
        return appUserAttentionRepository.countByAttentionId(userId);
    }

    @Override
    public void resetAppPassword(String mobile, String password) {
        AppUser appUser=appUserRepository.findByMobile(mobile);
        if(appUser==null){
            throw new BizException("账号不存在");
        }
        appUser.setLoginPass(new BCryptPasswordEncoder().encode(password));
        appUser.setUpdateTime(new Date());
        appUser.setUpdateBy(appUser.getNickName());
        appUserRepository.save(appUser);
    }

    @Override
    public void editAppUser(AppUser appUser) {
        appUserRepository.save(appUser);
    }
}
